﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CardLogistics.Web.Components;
using System.Data;
using CardLogistics.Model.Ordering;
using CardLogistics.Model.Approval;
using System.Text;
using CardLogistics.DAL.Purchase;
using CardLogistics.DAL;
using System.Text.RegularExpressions;
using CardLogistics.Model.Basic;

namespace CardLogistics.Web.MainPage.Ordering.Ordering_Cardinfo
{
    public partial class AddEdit : BasePage
    {
        private static readonly CardLogistics.DAL.Ordering.Ordering_CardInfoData DAL = new DAL.Ordering.Ordering_CardInfoData();
        private static readonly CardLogistics.DAL.Ordering.Ordering_DetailedData DetailDAL = new DAL.Ordering.Ordering_DetailedData();
        private static readonly CardLogistics.DAL.Purchase.Purchase_Contract_detailData ConDAL = new CardLogistics.DAL.Purchase.Purchase_Contract_detailData();
        protected Dictionary<string, string> CardTypeList = null;
        public string TitleName
        {
            get;
            set;
        }
        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            TitleName = GetStatusInfo(0, "卡片订货单");
            if (IsEdit)
            {
                CardTypeList = GetTypeList(null);
            }
            else
                CardTypeList = GetCardTypeList();
            if (!IsPostBack)
            {
                BindDLL(ddlCardTypeId, "BASIC_CARDTYPE", "CARDTYPENAME", "ID", " and STATUS=0 and ISDELETE=0");  //卡片类型
                ORDERDATA.Value = DateTime.Now.ToString("yyyy-MM-dd");//订单日期
                PIC.Value = LoggedUser.USERFULLNAME;//订单负责人默认为当前登录用户
                InitControl();
            }
        }
        #endregion

        #region 获取版面类型
        /// <summary>
        /// 初始化时调用版面信息
        /// </summary>
        /// <returns></returns>
        protected Dictionary<string, string> GetCardTypeList()
        {
            Dictionary<string, string> cardTypeList = new Dictionary<string, string>();
            cardTypeList = DetailDAL.GetCardTypeList();
            return cardTypeList;
        }

        /// <summary>
        /// 通过外键Id筛选版面信息
        /// </summary>
        /// <param name="conId">合同外键明细Id</param>
        /// <returns></returns>
        protected Dictionary<string, string> GetTypeList(string conId)
        {
            Dictionary<string, string> cardTypeList = new Dictionary<string, string>();
            string _key = Request.QueryString["id"];
            if (!string.IsNullOrEmpty(_key))
            {
                Ordering_CardInfo sData = DAL.GetModel(_key);
                conId = sData.CONID; //合同外键明细Id
            }
            cardTypeList = DetailDAL.GetTypeList(conId);
            return cardTypeList;
        }
        #endregion

        #region 绑定卡类型 根据合同明细ID获取需求单卡类型


        #endregion

        #region 得到一个对象实体
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public void InitControl()
        {
            if (IsEdit)
            {
                string _key = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(_key))
                {
                    Ordering_CardInfo sData = DAL.GetModel(_key);
                    SetWebControls(this.Page, sData);
                    //箱数
                    tdBOX.Value = (Convert.ToInt32(Regex.Replace(sData.ENDBOXNO, "[a-z]", "", RegexOptions.IgnoreCase)) - Convert.ToInt32(Regex.Replace(sData.STARTBOXNO, "[a-z]", "", RegexOptions.IgnoreCase)) + 1).ToString();
                    tdNO.Value = (Convert.ToInt32(sData.ENDNO) - Convert.ToInt32(sData.STARTNO) + 1).ToString();//卡张数 //- Convert.ToInt32(SpareParts.Value) 
                    SparePartsNum.Value = Convert.ToInt32(SpareParts.Value).ToString();//备品数量
                    PreMiumsNum.Value = Convert.ToInt32(PreMiums.Value).ToString();//赠品数量
                    PConNo.Value = sData.Pbatchno;//合同批次号
                    hf_ConId.Value = sData.CONID;//合同编号
                    //绑定卡类型 根据合同明细ID获取需求单卡类型
                    ddlCardTypeId.SelectedValue = sData.CARDTYPEID;//卡片类型
                    hf_EditSumCard.Value = (Convert.ToInt32(sData.ENDNO) - Convert.ToInt32(sData.STARTNO) + 1).ToString();
                    DataTable dt = DetailDAL.GetInfoById(sData.ID);//通过订单Id获取订单版面数量
                    string detId = "";
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            detId += dr["FormatType"].ToString() + "|" + dr["FormatNumber"].ToString() + ";";
                        }
                        hf_FormatId.Value = detId.TrimEnd(';');
                    }
                    btn_Add.Visible = btn_Submit.Visible = false;
                    if (sData.IsSubmit == 0 || sData.IsSubmit == 3)//状态为 0(未提交) 或 3(驳回)时才可以进行编辑操作
                    {
                        btn_Add.Visible = btn_Submit.Visible = true;
                    }
                    TitleName = GetStatusInfo(sData.IsSubmit, "卡片订货单");
                    //通过合同ID得到合同信息
                    string supStr = "";
                    GetConDetInfo(sData.CONID, out supStr);
                }
            }
            else
            {
                hf_EditSumCard.Value = "0";
                ORDERNO.Value = GetBillNumber("卡片订货单");
            }
        }
        #endregion

        #region 保存/提交
        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(0);
                ShowMegByResult(result, 0);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }

        /// <summary>
        /// 保存并提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(1);
                ShowMegByResult(result, 1);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }

        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="result"></param>
        private void ShowMegByResult(string result, int issubmit)
        {
            if (result.Split(',')[0] == "ok")
            {
                if (issubmit == 1)
                {
                    InsertAppInfo(2, result.Split(',')[1]); //2:卡片订货单审批
                    InsertLog("保存并提交订单信息,订单单号:" + ORDERNO.Value);
                }
                else
                    InsertLog("保存订单信息,订单单号:" + ORDERNO.Value);
                ReturnListInfo();
            }
            else
            {
                ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
            }
        }
        #endregion

        #region  卡片订货单实体
        /// <summary>
        /// 卡片订货单实体
        /// </summary>
        /// <returns></returns>
        private string EncapsulationModel(int issubmit)
        {
            string result = string.Empty;
            Ordering_CardInfo model = new Ordering_CardInfo();
            model = GetWebControls<Ordering_CardInfo>(this.Page);
            model.LASTUPDATEUSER = LoggedUser.ID;//最后修改人
            model.LASTUPDATEDATE = DateTime.Now; //最后修改时间
            model.CARDTYPEID = ddlCardTypeId.SelectedValue;//卡片类型
            model.CHIPTYPEID = "";//芯片类型
            model.CONID = hf_ConId.Value;//合同ID
            model.ORDERSTATUS = 0;//订单状态
            model.Details = hf_FormatId.Value + ";"; //订单详细数量
            model.IsSubmit = issubmit;//0 未提交 1 待审核 2 审核中 3 驳回 4 审核不通过 5审核通过
            model.SPAREPARTS = Convert.ToInt32(SparePartsNum.Value);//备品数量
            model.PREMIUMS = Convert.ToInt32(PreMiumsNum.Value);//赠品数量

            if (IsEdit)
            {
                model.ID = Request.QueryString["id"];
                result = DAL.Update(model);
            }
            else
            {
                result = DAL.Add(model);
                if (result.Split(',')[0] == "ok")
                {
                    ChgBillNumber("卡片订货单");
                }
            }
            return result;
        }
        #endregion

        #region 根据选择的合同明细获取详细信息
        /// <summary>
        /// 通过合同ID获取详细信息事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void TypeValue_Click(object sender, EventArgs e)
        {
            string conId = hf_ConId.Value;
            if (conId != "")
            {
                //新增时通过合同明细Id得到版面类型信息
                string supId = "";//供应商ID
                GetConDetInfo(conId, out supId);
                BATCHNO.Value = GetOrderBatch(supId);
                CardTypeList = GetTypeList(conId);
                //绑定卡类型 根据合同明细ID获取需求单卡类型
            }
        }

        /// <summary>
        /// 根据选择的合同明细获取详细信息
        /// </summary>
        /// <param name="conId">合同明细ID</param>
        private void GetConDetInfo(string conId, out string supId)
        {
            supId = "";//供应商ID
            DataTable dt = new Purchase_Contract_detailData().GetInfoById(conId);
            if (dt.Rows.Count > 0)
            {
                ConCardTotal.Value = dt.Rows[0]["allTotal"].ToString(); //合同明细总数量
                OredCardTotal.Value = dt.Rows[0]["dTotal"].ToString();//已订货数量

                lblConInfo.Text = "芯片类型:" + dt.Rows[0]["typename"].ToString();
                lblConInfo.Text += "  单价:" + decimal.Parse(dt.Rows[0]["PRICE"].ToString()).ToString("0.00") + "元/张";
                lblConInfo.Text += " 数量:" + dt.Rows[0]["CARDAMOUNT"].ToString() + "张";
                lblConInfo.Text += " 备品数量:" + dt.Rows[0]["SPAREPARTS"].ToString() + "张";
                lblConInfo.Text += " 赠品数量:" + dt.Rows[0]["PREMIUMS"].ToString() + "张";
                lblConInfo.Text += " 数量合计:" + dt.Rows[0]["allTotal"].ToString() + "张";
                lblConInfo.Text += " 金额合计:" + (decimal.Parse(dt.Rows[0]["PRICE"].ToString()) * decimal.Parse(dt.Rows[0]["CARDAMOUNT"].ToString())).ToString("0.00") + "元";
                supId = dt.Rows[0]["SuppId"].ToString();
                //新增时
                if (!IsEdit)
                {
                    string suppId = dt.Rows[0]["SuppId"].ToString();//供应商Id
                    //通过供应商Id获取箱号
                    if (suppId != null)
                    {
                        //获取最大编号
                        STARTBOXNO.Value = GetBoxStartNo(suppId);
                    }

                    //到货日期=订单日期 + 合同中的供货天数
                    GETDATA.Value = Convert.ToDateTime(ORDERDATA.Value).AddDays(Convert.ToInt32(DeliveryDays.Value.ToString())).ToString("yyyy-MM-dd");
                    string coId = dt.Rows[0]["ConId"].ToString();//合同Id
                    string startBoxNo = ""; //开始卡号
                    DataTable dv = CommonData.GetList("*", "v_ordering_cardinfo", "ConId='" + conId + "' and issubmit<>4  order by LastUpdateDate desc");
                    if (dv.Rows.Count > 0)
                    {
                        // 开始卡号
                        startBoxNo = dv.Rows[0]["StartBoxNo"].ToString();
                        //赠品数量
                        int preMiumsNum = Convert.ToInt32(PreMiums.Value) - Convert.ToInt32(dv.Compute("sum(PREMIUMS)", ""));
                        if (preMiumsNum >= 0)
                        {
                            PreMiumsNum.Value = preMiumsNum.ToString();
                            PreMiums.Value = preMiumsNum.ToString();//给隐藏域赋值
                        }
                        else
                        {
                            PreMiumsNum.Value = "0";
                            PreMiums.Value = "0";//给隐藏域赋值
                        }
                    }
                    else
                        //赠品数量
                        PreMiumsNum.Value = Convert.ToInt32(PreMiums.Value).ToString();
                }
            }
        }

        #endregion

        #region 根据合同id获取订货单批次号
        private string GetOrderBatch(string cId)
        {
            Basic_Suppliers modelSup = new DAL.Basic.Basic_SuppliersData().GetModel(cId);
            string sCode = modelSup.SUPPLIERSCODE.ToUpper();
            DataTable dtOrder = DbHelperSQL.GetQueryResult(" select batchno from ordering_cardinfo where batchno like '%" + sCode + "%' order by batchno desc ");
            if (dtOrder != null && dtOrder.Rows.Count > 0)
            {
                string maxBatch = dtOrder.Rows[0][0].ToString();
                string afterCode = maxBatch.Substring(0, maxBatch.Length - 3).ToUpper();
                if (afterCode == "YKT" + DateTime.Now.ToString("yyyy") + sCode)
                {
                    try
                    {
                        int lastNum = int.Parse(maxBatch.Substring(maxBatch.Length - 3,3)) + 1;
                        return "YKT" + DateTime.Now.ToString("yyyy") + sCode + lastNum.ToString().PadLeft(3, '0');
                    }
                    catch
                    {
                        return "";
                    }
                }
                else
                {
                    return "YKT" + DateTime.Now.ToString("yyyy") + sCode + "001";
                }
            }

            else
            {
                return "YKT" + DateTime.Now.ToString("yyyy") + sCode + "001";
            }
            return "";
        }
        #endregion
    }
}